/*
 * Copyright 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.howdee.howdyags;

import com.howdee.howdyags.actionbar.ActionBarActivity;
import com.howdee.howdyags.settings.SettingsActivity;
import com.howdee.howdyags.R;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
    private static WebView mWebView;
	private AutoRefreshTask mAutoRefreshTask;
	private boolean refreshing;
	private boolean navigatingBack;

	private static final int MAX_AUTO_REFRESH_SECONDS = 600;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
		
		mWebView = (WebView) findViewById(R.id.webview);
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setSavePassword(true);
		webSettings.setSupportZoom(false);
		mWebView.setWebViewClient(new TexAgsWebViewClient());
		
		mWebView.loadUrl("http://" + getString(R.string.texags_mobile) + "/");
		
		getActionBar().setHomeButtonEnabled(true);
    }
    
    // Handles screen rotations and opening the keyboard
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
    }

    
    @Override
    protected void onPause() {
    	// Stop auto refresh when pausing/leaving app
    	if(mAutoRefreshTask!=null && mAutoRefreshTask.isRunning()) {
    		mAutoRefreshTask.stop();
            Toast.makeText(this, getString(R.string.msg_auto_refresh_disabled), Toast.LENGTH_SHORT).show();
    	}
    	
    	super.onPause();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main, menu);

        // Calling super after populating the menu is necessary here to ensure that the
        // action bar helpers have a chance to handle this event.
        return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
            	//if(mWebView.canGoBack())
            	goBack();
            	//else if(prefAltHomepage)
            	//	mWebView.loadUrl("http://" + getString(R.string.texags_mobile) + "/");
                break;

            case R.id.menu_share:
                share();
                break;
                
            case R.id.menu_auto_refresh:
            	setAutoRefresh();
            	break;

            case R.id.menu_refresh:
                getActionBarHelper().setRefreshActionItemState(true);
				refresh();
                break;
                
            case R.id.menu_copy_url:
            	copyUrl();
            	break;
                
            case R.id.menu_settings:
            	startActivity(new Intent(this, SettingsActivity.class));
            	break;
        }
        return super.onOptionsItemSelected(item);
    }

	private void share() {
		// TODO: Prompt whether to share mobile or full version
		Intent shareIntent = new Intent();
		shareIntent.setAction(Intent.ACTION_SEND);
		shareIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
		shareIntent.setType("text/plain");
		startActivity(shareIntent);
	}
    
    private void setAutoRefresh() {
    	if(mAutoRefreshTask!=null && mAutoRefreshTask.isRunning()) {
    		mAutoRefreshTask.stop();
            Toast.makeText(this, getString(R.string.msg_auto_refresh_disabled), Toast.LENGTH_SHORT).show();
    	}
    	else {
	    	String seconds = " " + getString(R.string.time_seconds);
	    	String minute = " " + getString(R.string.time_minute);
	    	
			final String[] intervals = {5 + seconds, 10 + seconds, 30 + seconds, 1 + minute};
	    	final int[] values = {5, 10, 30, 1*60};
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(R.string.prompt_interval);
			builder.setItems(intervals, new DialogInterface.OnClickListener() {
				@SuppressWarnings("unchecked")
				public void onClick(DialogInterface dialog, int which) {
					mAutoRefreshTask = new AutoRefreshTask(values[which]);
					mAutoRefreshTask.execute();
		            Toast.makeText(MainActivity.this, getString(R.string.msg_auto_refresh_enabled), Toast.LENGTH_SHORT).show();
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
    	}
	}

	private void refresh() {
		if (mWebView.getProgress()==0 || mWebView.getProgress()==100) {
			refreshing = true;
			mWebView.reload();
		}
	}

	private void goBack() {
		navigatingBack = true;
		mWebView.goBack();
	}
	
	private void copyUrl() {
		ClipboardManager clipBoard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
		clipBoard.setPrimaryClip(ClipData.newPlainText("TexAgs page", mWebView.getUrl()));
        Toast.makeText(this, getString(R.string.msg_url_copied), Toast.LENGTH_SHORT).show();
	}

	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's history
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	
        	//Disable auto refresh if active
        	if(mAutoRefreshTask!=null && mAutoRefreshTask.isRunning()) {
        		mAutoRefreshTask.stop();
                Toast.makeText(this, getString(R.string.msg_auto_refresh_disabled), Toast.LENGTH_SHORT).show();
        	}
        	
        	if(mWebView.canGoBack()) {
	        	goBack();
	            return true;
        	}
        	//else if(prefAltHomepage)
        	//	mWebView.loadUrl("http://" + getString(R.string.texags_mobile) + "/");
        }
        // If it wasn't the Back key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }
    
    private class TexAgsWebViewClient extends WebViewClient {
        private static final int HEADER_AND_AD_HEIGHT = 128;

		@Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if(mAutoRefreshTask!=null && mAutoRefreshTask.isRunning()) {
				mAutoRefreshTask.stop();
	            Toast.makeText(MainActivity.this, getString(R.string.msg_auto_refresh_disabled), Toast.LENGTH_SHORT).show();
			}
			
        	String host = Uri.parse(url).getHost();
            String texAgsMobile = getString(R.string.texags_mobile);
            String texAgsM = getString(R.string.texags_m);
            String texAgsV4 = getString(R.string.texags_v4);
            String texAgsCom = getString(R.string.texags_com);
            
        	// Intentionally not handling "www.texags.com" host so that full site opens externally
			if (host.equalsIgnoreCase(texAgsMobile) 
            		|| host.equalsIgnoreCase(texAgsM)
            		|| host.equalsIgnoreCase(texAgsV4)
            		|| host.equalsIgnoreCase(texAgsCom)) {
                // Do not override; let my WebView load the page
                return false;
            }
            // Otherwise, launch another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
		
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			getActionBarHelper().setRefreshActionItemState(true);
			getActionBar().setHomeButtonEnabled(mWebView.canGoBack());
			getActionBar().setDisplayHomeAsUpEnabled(mWebView.canGoBack());
			interpretUrl(url);
		}
        
        @Override
        public void onPageFinished(WebView view, String url) {
        	getActionBarHelper().setRefreshActionItemState(false);
        	
        	if(!refreshing && !navigatingBack)
        		view.scrollTo(0, HEADER_AND_AD_HEIGHT);
        	
        	refreshing = false;
        	navigatingBack = false;
        }
    }
    
    @SuppressWarnings("rawtypes")
	public class AutoRefreshTask extends AsyncTask {
    	
		private int mSeconds;
    	
		private AutoRefreshTask(int seconds) {
    		mSeconds = seconds;
    	}
		
		@SuppressWarnings("unchecked")
		@Override
		protected Object doInBackground(Object... arg0) {
			try {
				// Repeat for a maximum amount of seconds
				for(int i=0; i<MAX_AUTO_REFRESH_SECONDS; i+=mSeconds) {
					// Using this as the asynchronous call to refresh the webview (executes onProgressUpdate() in the main thread)
					publishProgress();
					Thread.sleep(mSeconds * 1000);
				}
			} catch (InterruptedException e) {
			}
			return null;
		}
    	
		@Override
		protected void onProgressUpdate(Object... values) {
			refresh();
		}

		public void stop() {
			if(isRunning())
				cancel(true);
		}
		
		public boolean isRunning() {
			return getStatus()==AsyncTask.Status.RUNNING;
		}
    }

	public void interpretUrl(String url) {
		
	}
}
